package com.agentlab.imitation.mail;

import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


public class EmailSender {
    private static final String charset = "GBK";
    private static final String defaultMimetype = "text/plain";
    
    public static void main(String[] args) throws Exception {
    	EmailSender.send(new String[]{"heming07@swu.edu.cn"},
    			"测试5", "<b>邮件发送5</b>", null , "text/html");
    	//"text/html" "text/plain"
    }
    /**
     * 发送邮件
     * @param receiver 收件人
     * @param subject 标题
     * @param mailContent 邮件内容
     * @param mimetype 内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
     * @throws Exception 
     */
    public static void send(String receiver, String subject, String mailContent, String mimetype) throws Exception {
    	send(new String[]{receiver}, subject, mailContent, mimetype);
    }
    /**
     * 发送邮件
     * @param receivers 收件人
     * @param subject 标题
     * @param mailContent 邮件内容
     * @param mimetype 内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
     * @throws Exception 
     */
    public static void send(String[] receivers, String subject, String mailContent, String mimetype) throws Exception {
    	send(receivers, subject, mailContent, null, mimetype);
    }
    /**
     * 发送邮件
     * @param receivers 收件人
     * @param subject 标题
     * @param mailContent 邮件内容
     * @param attachements 附件
     * @param mimetype 内容类型 默认为text/plain,如果要发送HTML内容,应设置为text/html
     * @throws Exception 
     */

    public static void send(String[] receivers, String subject, String mailContent, File[] attachements, String mimetype) throws Exception {
        Properties props = new Properties();
       
        try {
	        props.put("mail.smtp.host", "smtp.swu.edu.cn");//smtp服务器地址 sohu
	        props.put("mail.smtp.auth", "true");//需要校验
	        Session session = Session.getDefaultInstance(props, new Authenticator() {
	            protected PasswordAuthentication getPasswordAuthentication() {
	                return new PasswordAuthentication("heming07@swu.edu.cn","woaijia");//登录用户名/密码
	            }
	        });
	        session.setDebug(true);
	       
	        MimeMessage mimeMessage = new MimeMessage(session);
	        mimeMessage.setFrom(new InternetAddress("heming07@swu.edu.cn"));//发件人邮件
	
	        InternetAddress[] bccAddress = new InternetAddress[receivers.length];
	        for (int i=0; i<receivers.length; i++) {
	            bccAddress[i] = new InternetAddress(receivers[i]);
	        }
	       
	        //mimeMessage.setRecipients(Message.RecipientType.TO, "info@flowerdeluce.com");//收件人邮件
	        mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddress);//暗送
	        mimeMessage.setSubject(subject, charset); //charset gbk
	      
	        Multipart multipart = new MimeMultipart();
	        //正文
	        MimeBodyPart body = new MimeBodyPart();
	       // body.setText(message, charset);不支持html
	        body.setContent(mailContent, (mimetype!=null && !"".equals(mimetype) ? mimetype : defaultMimetype)+ ";charset="+ charset);
	        multipart.addBodyPart(body);//发件内容
	        //附件
	        if(attachements!=null){
	            for (File attachement : attachements) {
	                MimeBodyPart attache = new MimeBodyPart();
	               //ByteArrayDataSource bads = new ByteArrayDataSource(byte[],"application/x-any");
	                attache.setDataHandler(new DataHandler(new FileDataSource(attachement)));
	                String fileName = getLastName(attachement.getName());
	                attache.setFileName(MimeUtility.encodeText(fileName, charset, null));
	                //MimeUtility.encodeWord(arg0);
	                multipart.addBodyPart(attache);
	            }
	        }
	        mimeMessage.setContent(multipart);
	       // SimpleDateFormat formcat = new SimpleDateFormat("yyyy-MM-dd");            
	        mimeMessage.setSentDate(new Date());//formcat.parse("2010-5-23")
	        Transport.send(mimeMessage);  
	        
        } catch (Exception e) {
        	//e.printStackTrace();
        	throw new Exception("发送Email异常。");
        }
    }

    private static String getLastName(String fileName) {
        int pos = fileName.lastIndexOf("\\");
        if (pos > -1) {
            fileName = fileName.substring(pos + 1);
        }
        pos = fileName.lastIndexOf("/");
        if (pos > -1) {
            fileName = fileName.substring(pos + 1);
        }
        return fileName;
    }
    public static void test() throws Exception {

		try {
			Properties prop = new Properties();
			// Set the default enveloppe sender address
			prop.setProperty("mail.davmail.from", "tanglf@flowerdeluce.com");
			//prop.setProperty("164918278.pamx1.hotmail.com", "tanglf@flowerdeluce.com");
			Session ses = Session.getInstance(prop);

			// Create the transport connection
			Transport transport = ses.getTransport("davmail_xmit");
			transport.connect(null, "tanglf@flowerdeluce.com", "123456");
 			
 			// Prepare the message
			MimeMessage txMsg = new MimeMessage(ses);
			txMsg.setSubject("Test subject");
			
			InternetAddress addrFrom = new InternetAddress("tanglf@flowerdeluce.com");
			txMsg.setFrom(addrFrom);
			
			InternetAddress addrTo = new InternetAddress("action8831@hotmail.com", "tanglangrong@163.com");
			txMsg.addRecipient(Message.RecipientType.TO, addrTo);
			
			txMsg.setText("Hello world !");
			txMsg.setSentDate(new Date());
			
			// Send the message
 			transport.sendMessage(txMsg, txMsg.getAllRecipients());
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
